<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue'
import { DeleteOutlined, PlusOutlined } from '@ant-design/icons-vue'
import type { PhaseType } from '@/types/micro-scene'
import { message } from 'ant-design-vue'
import uniqueId from 'lodash/uniqueId'
import { useRoute } from 'vue-router'
import { updateScenePhaseList } from '@/api/MicroScene/MicroSceneDetailApi'
const props = defineProps<{
  visible: boolean,
  currentPhaseId: string,
  phaseList: PhaseType[]
}>()
const emit = defineEmits(['update:visible', 'update:currentPhaseId', 'update:phaseList'])
const route = useRoute()
const form = ref({
  phaseTitle: '',
})

const microSceneId: string = route.params.id as string

// 创建缓存，应该是拷贝defaultPhases，而不是直接引用
const cachePhases = ref<PhaseType[]>(props.phaseList.map(phase => ({ ...phase })))

watch(() => props.phaseList, (newPhaseList) => {
  if (newPhaseList && newPhaseList.length > 0)
    cachePhases.value = newPhaseList.map(phase => ({ ...phase }))
}, { immediate: true })

onMounted(() => {
  // 每次进入页面创建缓存，添加空值检查
  if (props.phaseList && props.phaseList.length > 0)
    cachePhases.value = props.phaseList.map(phase => ({ ...phase }))
})

const handleOk = async () => {
  try {
    // 去除isOff为true的阶段
    const tmpPhases = cachePhases.value.filter(phase => !phase.isOff)
    // 禁止将所有阶段全部删除，至少保留一个阶段
    if (tmpPhases.length === 0) {
      message.error('至少保留一个阶段')
      return
    }

    // 去除cachePhases中isNew和isOff都为true的阶段
    cachePhases.value = cachePhases.value.filter(phase => !phase.isOff || !phase.isNew)

    // 先更新后端
    await updateScenePhaseList(microSceneId, cachePhases.value)

    // 同时更新缓存
    cachePhases.value = tmpPhases
    // 更新phaseList，需要传递新的阶段列表
    emit('update:phaseList')

    // 判断如果当前阶段不存在，则默认选中第一个阶段
    if (tmpPhases.findIndex(phase => phase.phaseId === props.currentPhaseId) === -1)
      emit('update:currentPhaseId', tmpPhases[0].phaseId)
    // 更新成功后再更新UI
    emit('update:visible', false)
  }
  catch (error) {
    console.error('更新阶段列表失败:', error)
    message.error('更新阶段列表失败')
  }
}

const handleCancel = () => {
  emit('update:visible', false)
  // 取消缓存恢复
  cachePhases.value = props.phaseList.map(phase => ({ ...phase }))
}

// note: 即使删除阶段，也不是在直接从数组移除，而是isOff为true，isOff为true的阶段不会被展示
const handleDeletePhase = (phaseId: string) => {
  // 将删除的阶段设置为isOff为true
  const phase = cachePhases.value.find(phase => phase.phaseId === phaseId)
  if (phase)
    phase.isOff = true
}

// 在当前阶段之前插入一个新阶段
const handleInsertPhaseBefore = (phaseId: string) => {
  const phase = cachePhases.value.find(phase => phase.phaseId === phaseId)
  const phaseIndex = cachePhases.value.findIndex(phase => phase.phaseId === phaseId)
  // 插入一个新阶段到当前阶段之前
  if (phase) {
    const newPhase: PhaseType = { phaseId: uniqueId(), phaseTitle: '新阶段', sortOrder: phase.sortOrder, isNew: true }
    for (let i = phaseIndex; i < cachePhases.value.length; i++) {
      // 修改该阶段之后的所有阶段sortOrder+1
      cachePhases.value[i].sortOrder++
    }
    // 插入新阶段
    cachePhases.value.splice(phaseIndex, 0, newPhase)
  }
}

// 在当前阶段之后插入一个新阶段
const handleInsertPhaseAfter = (phaseId: string) => {
  const phase = cachePhases.value.find(phase => phase.phaseId === phaseId)
  const phaseIndex = cachePhases.value.findIndex(phase => phase.phaseId === phaseId)
  // 插入一个新阶段到当前阶段之后
  if (phase) {
    const newPhase: PhaseType = { phaseId: uniqueId(), phaseTitle: '新阶段', sortOrder: phase.sortOrder + 1, isNew: true }
    for (let i = phaseIndex + 1; i < cachePhases.value.length; i++) {
      // 修改该阶段之后的所有阶段sortOrder+1
      cachePhases.value[i].sortOrder++
    }
    // 插入新阶段
    cachePhases.value.splice(phaseIndex + 1, 0, newPhase)
  }
}
</script>

<template>
  <a-modal :open="visible" title="编辑阶段" @ok="handleOk" @cancel="handleCancel">
    <a-form :model="form" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
      <a-form-item v-for="(phase, index) in cachePhases" v-show="!phase.isOff" :key="phase.phaseId" :label="`阶段${index + 1}`">
        <a-space>
          <a-input v-model:value="phase.phaseTitle" />
          <a-button type="primary" danger @click="handleDeletePhase(phase.phaseId as string)">
            <template #icon>
              <DeleteOutlined />
            </template>
          </a-button>
          <a-dropdown trigger="click">
            <a-button type="primary">
              <template #icon>
                <PlusOutlined />
              </template>
            </a-button>
            <template #overlay>
              <a-menu>
                <a-menu-item key="1" @click="handleInsertPhaseBefore(phase.phaseId as string)">
                  向上添加
                </a-menu-item>
                <a-menu-item key="2" @click="handleInsertPhaseAfter(phase.phaseId as string)">
                  向下添加
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </a-space>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
